package cloudspace.vm.filesystem;

import java.io.File;
import java.io.IOException;

import org.zkoss.zk.ui.Executions;

import cloudspace.config.CloudSpaceConfiguration;


public class ProjectSpec
{
    // ~ Constructors ..........................................................

    // ----------------------------------------------------------
    private ProjectSpec()
    {
        // Prevent instantiation.
    }


    // ~ Methods ...............................................................

    // ----------------------------------------------------------
    public static void createProject( CSPath projectDirectory )
        throws IOException
    {
        CSPath metaData = new CSPath( projectDirectory, META_NAME );
        CSPathWriter metaWriter = new CSPathWriter( metaData );
        metaWriter.write( "classpath: ." );
        metaWriter.close();

    }


    // ----------------------------------------------------------
    public static boolean isProjectDirectory( CSPath projDir )
    {
        if ( projDir.isDirectory() )
        {
            CSPath metaFile = new CSPath( projDir, META_NAME );

            return metaFile.exists();
        }

        return false;
    }


    // ----------------------------------------------------------
    public static boolean isProjectDirectory( File projDir )
    {
        if ( projDir.isDirectory() )
        {
            File metaFile = new File( projDir, META_NAME );

            return metaFile.exists();
        }

        return false;
    }


    /*
     * public static File[] cleanMetaOut(File[] files) { if(files == null) {
     * return files; } List<File> cleanList = new ArrayList<File>(); for (File
     * file : files) { if (!file.getName().equals(metaName)) {
     * cleanList.add(file); } } return cleanList.toArray(new File[0]); }
     */

    public static String getBaseProjectDir( String baseDir )
    {
        File localDir = new File( baseDir );
        if ( isProjectDirectory( localDir )
            || localDir.getPath().equals( Executions.getCurrent()
                .getDesktop()
                .getWebApp()
                .getRealPath( "" ) ) )
        {
            return baseDir;
        }
        localDir = localDir.getParentFile();
        while ( localDir != null
            && !localDir.getPath()
                .equals( CloudSpaceConfiguration.getInstance()
                    .getStorageLocation() )
            && !localDir.getPath().equals( Executions.getCurrent()
                .getDesktop()
                .getWebApp()
                .getRealPath( "" ) ) )
        {
            if ( isProjectDirectory( localDir ) )
            {
                return localDir.getPath();
            }
            localDir = localDir.getParentFile();
        }
        return baseDir;
    }

    // ~ Static/instance variables .............................................

    private static final String META_NAME = "project.info";
}
